package com.maben.udp.test002;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 聊天发送端
 */
public class ChatSender implements Runnable {
    DatagramSocket socket;
    String fromHostName;
    int fromPort;
    String toHostName;
    int toPort;

    public ChatSender(String fromHostName, int fromPort, String toHostName, int toPort) {
        try {
            this.socket = new DatagramSocket(fromPort);
            this.fromHostName = fromHostName;
            this.fromPort = fromPort;
            this.toHostName = toHostName;
            this.toPort = toPort;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        try {
            while (true) {
                String s = bufferedReader.readLine();
                byte[] data = s.getBytes();
                DatagramPacket packet = new DatagramPacket(data, 0, data.length, new InetSocketAddress(toHostName, toPort));
                socket.send(packet);
                if (s.equals("bye"))
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            socket.close();
        }
    }
}